import React, { useState, useEffect } from 'react'
import { Card, Button, Space, Modal, message, Tabs, Descriptions, Tag, Row, Col } from 'antd'
import { PlusOutlined, EditOutlined, DeleteOutlined, SolutionOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import DataTable from '../../../components/common/DataTable'
import Form from '../../../components/common/Form'

// 引入API
import { listRecruitments, createRecruitment, getRecruitment, updateRecruitment, deleteRecruitment } from '../../../api/recruitment'

const { confirm } = Modal

const Recruitment = () => {
    const [loading, setLoading] = useState(false)
    const [dataSource, setDataSource] = useState([])
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [visible, setVisible] = useState(false)
    const [currentRecruitment, setCurrentRecruitment] = useState(null)
    const [viewVisible, setViewVisible] = useState(false)
    const [viewRecruitment, setViewRecruitment] = useState(null)
    
    // 获取当前用户角色
    const userRole = localStorage.getItem('userRole')



    useEffect(() => {
        fetchRecruitments()
    }, [pagination.current, pagination.pageSize])

    // 获取招聘数据
    const fetchRecruitments = async () => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize
            }
            const response = await listRecruitments(params)
            setDataSource(response.data)
            setPagination({
                ...pagination,
                total: response.total
            })
        } catch (error) {
            console.error('获取招聘列表失败:', error)
            message.error('获取招聘列表失败')
        } finally {
            setLoading(false)
        }
    }

    // 处理表格变化
    const handleTableChange = (pagination) => {
        setPagination(pagination)
    }

    // 处理搜索
    const handleSearch = async (value) => {
        setLoading(true)
        try {
            const params = {
                page: pagination.current,
                pageSize: pagination.pageSize,
                keyword: value
            }
            const response = await listRecruitments(params)
            setDataSource(response.data)
            setPagination({
                ...pagination,
                total: response.total
            })
        } catch (error) {
            console.error('搜索招聘失败:', error)
            message.error('搜索招聘失败')
        } finally {
            setLoading(false)
        }
    }

    // 添加招聘
    const handleAdd = () => {
        setCurrentRecruitment(null)
        setVisible(true)
    }

    // 编辑招聘
    const handleEdit = async (record) => {
        try {
            setLoading(true)
            // 获取最新的招聘详情
            const response = await getRecruitment(record.id)
            setCurrentRecruitment(response.data)
            setVisible(true)
        } catch (error) {
            console.error('获取招聘详情失败:', error)
            message.error('获取招聘详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 查看招聘详情
    const handleView = async (record) => {
        try {
            setLoading(true)
            // 获取最新的招聘详情
            const response = await getRecruitment(record.id)
            setViewRecruitment(response.data)
            setViewVisible(true)
        } catch (error) {
            console.error('获取招聘详情失败:', error)
            message.error('获取招聘详情失败')
        } finally {
            setLoading(false)
        }
    }

    // 删除招聘
    const handleDelete = (id) => {
        confirm({
            title: '确认删除',
            icon: <ExclamationCircleOutlined />,
            content: '确定要删除这个招聘职位吗？此操作不可恢复。',
            onOk: async () => {
                try {
                    setLoading(true)
                    await deleteRecruitment(id)
                    message.success('删除成功')
                    // 重新获取列表数据
                    fetchRecruitments()
                } catch (error) {
                    console.error('删除招聘失败:', error)
                    message.error('删除招聘失败')
                } finally {
                    setLoading(false)
                }
            }
        })
    }

    // 表单提交
    const handleFormSubmit = async (values) => {
        try {
            setLoading(true)
            if (currentRecruitment) {
                // 编辑招聘
                await updateRecruitment(currentRecruitment.id, values)
                message.success('编辑成功')
            } else {
                // 添加招聘
                await createRecruitment(values)
                message.success('添加成功')
            }
            // 关闭模态框
            setVisible(false)
            // 重新获取列表数据
            fetchRecruitments()
        } catch (error) {
            console.error('保存招聘失败:', error)
            message.error('保存招聘失败')
        } finally {
            setLoading(false)
        }
    }

    // 表格列定义
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            key: 'id',
            width: 80
        },
        {
            title: '职位名称',
            dataIndex: 'title',
            key: 'title',
            render: (text, record) => (
                <a onClick={() => handleView(record)}>{text}</a>
            )
        },
        {
            title: '部门',
            dataIndex: 'department',
            key: 'department'
        },
        {
            title: '招聘人数',
            dataIndex: 'count',
            key: 'count'
        },
        {
            title: '薪资范围',
            dataIndex: 'salary',
            key: 'salary'
        },
        {
            title: '工作地点',
            dataIndex: 'location',
            key: 'location'
        },
        {
            title: '状态',
            dataIndex: 'status',
            key: 'status',
            render: (text) => {
                let color = text === '招聘中' ? 'green' : 'volcano'
                return <Tag color={color}>{text}</Tag>
            }
        },
        {
            title: '截止日期',
            dataIndex: 'deadline',
            key: 'deadline'
        },
        {
            title: '申请人数',
            dataIndex: 'applicationCount',
            key: 'applicationCount'
        },
        {
            title: '操作',
            key: 'action',
            width: 180,
            render: (_, record) => (
                <Space size="middle">
                    <Button 
                        type="text" 
                        icon={<EditOutlined />} 
                        onClick={() => handleEdit(record)}
                    >
                        编辑
                    </Button>
                    <Button 
                        type="text" 
                        danger 
                        icon={<DeleteOutlined />} 
                        onClick={() => handleDelete(record.id)}
                    >
                        删除
                    </Button>
                </Space>
            )
        }
    ]

    return (
        <div className="recruitment-container">
            <Card title="招聘管理" extra={
                userRole === 'admin' && (
                    <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
                        添加招聘
                    </Button>
                )
            }>
                <DataTable 
                    columns={columns}
                    dataSource={dataSource}
                    loading={loading}
                    rowKey="id"
                    pagination={pagination}
                    onChange={handleTableChange}
                    onSearch={handleSearch}
                    onRefresh={fetchRecruitments}
                    searchPlaceholder="搜索职位名称/部门/地点"
                />
            </Card>

            {/* 招聘表单模态框 */}
            <Modal
                title={currentRecruitment ? '编辑招聘' : '添加招聘'}
                open={visible}
                onCancel={() => setVisible(false)}
                footer={null}
                width={700}
            >
                <Form
                    initialValues={currentRecruitment}
                    onFinish={handleFormSubmit}
                    labelCol={{ span: 4 }}
                    wrapperCol={{ span: 20 }}
                >
                    <Form.Item
                        name="title"
                        label="职位名称"
                        rules={[{ required: true, message: '请输入职位名称' }]}
                    >
                        <input placeholder="请输入职位名称" />
                    </Form.Item>
                    <Form.Item
                        name="department"
                        label="所属部门"
                        rules={[{ required: true, message: '请选择所属部门' }]}
                    >
                        <select>
                            <option value="人事部">人事部</option>
                            <option value="技术部">技术部</option>
                            <option value="市场部">市场部</option>
                            <option value="财务部">财务部</option>
                            <option value="管理部">管理部</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="count"
                        label="招聘人数"
                        rules={[{ required: true, message: '请输入招聘人数' }]}
                    >
                        <input type="number" placeholder="请输入招聘人数" />
                    </Form.Item>
                    <Form.Item
                        name="salary"
                        label="薪资范围"
                        rules={[{ required: true, message: '请输入薪资范围' }]}
                    >
                        <input placeholder="请输入薪资范围，如：10k-15k" />
                    </Form.Item>
                    <Form.Item
                        name="location"
                        label="工作地点"
                        rules={[{ required: true, message: '请输入工作地点' }]}
                    >
                        <input placeholder="请输入工作地点" />
                    </Form.Item>
                    <Form.Item
                        name="experience"
                        label="工作经验"
                        rules={[{ required: true, message: '请输入工作经验要求' }]}
                    >
                        <input placeholder="请输入工作经验要求，如：3-5年" />
                    </Form.Item>
                    <Form.Item
                        name="education"
                        label="学历要求"
                        rules={[{ required: true, message: '请输入学历要求' }]}
                    >
                        <input placeholder="请输入学历要求，如：本科及以上" />
                    </Form.Item>
                    <Form.Item
                        name="description"
                        label="职位描述"
                        rules={[{ required: true, message: '请输入职位描述' }]}
                    >
                        <textarea placeholder="请输入职位描述" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="requirements"
                        label="任职要求"
                        rules={[{ required: true, message: '请输入任职要求' }]}
                    >
                        <textarea placeholder="请输入任职要求" rows={4} />
                    </Form.Item>
                    <Form.Item
                        name="status"
                        label="状态"
                        rules={[{ required: true, message: '请选择状态' }]}
                    >
                        <select>
                            <option value="招聘中">招聘中</option>
                            <option value="已结束">已结束</option>
                        </select>
                    </Form.Item>
                    <Form.Item
                        name="publishDate"
                        label="发布日期"
                        rules={[{ required: true, message: '请选择发布日期' }]}
                    >
                        <input type="date" />
                    </Form.Item>
                    <Form.Item
                        name="deadline"
                        label="截止日期"
                        rules={[{ required: true, message: '请选择截止日期' }]}
                    >
                        <input type="date" />
                    </Form.Item>
                </Form>
            </Modal>

            {/* 招聘详情模态框 */}
            <Modal
                title="招聘详情"
                open={viewVisible}
                onCancel={() => setViewVisible(false)}
                footer={null}
                width={700}
            >
                {viewRecruitment && (
                    <div className="recruitment-detail">
                        <Row gutter={[16, 16]}>
                            <Col span={24}>
                                <Tabs defaultActiveKey="1">
                                    <Tabs.TabPane tab="基本信息" key="1">
                                        <Descriptions bordered column={2}>
                                            <Descriptions.Item label="ID">{viewRecruitment.id}</Descriptions.Item>
                                            <Descriptions.Item label="职位名称">{viewRecruitment.title}</Descriptions.Item>
                                            <Descriptions.Item label="所属部门">{viewRecruitment.department}</Descriptions.Item>
                                            <Descriptions.Item label="招聘人数">{viewRecruitment.count}</Descriptions.Item>
                                            <Descriptions.Item label="薪资范围">{viewRecruitment.salary}</Descriptions.Item>
                                            <Descriptions.Item label="工作地点">{viewRecruitment.location}</Descriptions.Item>
                                            <Descriptions.Item label="工作经验">{viewRecruitment.experience}</Descriptions.Item>
                                            <Descriptions.Item label="学历要求">{viewRecruitment.education}</Descriptions.Item>
                                            <Descriptions.Item label="发布日期">{viewRecruitment.publishDate}</Descriptions.Item>
                                            <Descriptions.Item label="截止日期">{viewRecruitment.deadline}</Descriptions.Item>
                                            <Descriptions.Item label="状态">
                                                <Tag color={viewRecruitment.status === '招聘中' ? 'green' : 'volcano'}>
                                                    {viewRecruitment.status}
                                                </Tag>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="申请人数">{viewRecruitment.applicationCount}</Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    <Tabs.TabPane tab="职位详情" key="2">
                                        <Descriptions bordered column={1}>
                                            <Descriptions.Item label="职位描述">
                                                <div style={{ whiteSpace: 'pre-line' }}>{viewRecruitment.description}</div>
                                            </Descriptions.Item>
                                            <Descriptions.Item label="任职要求">
                                                <div style={{ whiteSpace: 'pre-line' }}>{viewRecruitment.requirements}</div>
                                            </Descriptions.Item>
                                        </Descriptions>
                                    </Tabs.TabPane>
                                    {userRole === 'admin' && (
                                        <Tabs.TabPane tab="投递信息" key="3">
                                            <DataTable 
                                                columns={[
                                                    { title: '应聘者', dataIndex: 'applicantName', key: 'applicantName' },
                                                    { title: '投递时间', dataIndex: 'applyDate', key: 'applyDate' },
                                                    { title: '状态', dataIndex: 'status', key: 'status',
                                                        render: (text) => (
                                                            <Tag color={text === '待处理' ? 'orange' : text === '已通过' ? 'green' : 'red'}>
                                                                {text}
                                                            </Tag>
                                                        )
                                                    },
                                                    { title: '操作', key: 'action',
                                                        render: (_, record) => (
                                                            <Button type="link" onClick={() => handleViewApplication(record)}>
                                                                查看详情
                                                            </Button>
                                                        )
                                                    }
                                                ]}
                                                dataSource={viewRecruitment.applications || []}
                                                rowKey="id"
                                            />
                                        </Tabs.TabPane>
                                    )}
                                </Tabs>
                            </Col>
                        </Row>
                    </div>
                )}
            </Modal>
        </div>
    )
}

// 查看应聘申请详情
const handleViewApplication = (record) => {
    Modal.info({
        title: '应聘申请详情',
        width: 700,
        content: (
            <Descriptions bordered column={2}>
                <Descriptions.Item label="应聘者">{record.applicantName}</Descriptions.Item>
                <Descriptions.Item label="投递时间">{record.applyDate}</Descriptions.Item>
                <Descriptions.Item label="状态">
                    <Tag color={record.status === '待处理' ? 'orange' : record.status === '已通过' ? 'green' : 'red'}>
                        {record.status}
                    </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="简历状态">{record.resumeStatus}</Descriptions.Item>
                <Descriptions.Item label="联系电话" span={2}>{record.phone}</Descriptions.Item>
                <Descriptions.Item label="电子邮箱" span={2}>{record.email}</Descriptions.Item>
                <Descriptions.Item label="求职意向" span={2}>{record.jobIntention}</Descriptions.Item>
                <Descriptions.Item label="备注" span={2}>{record.remarks || '-'}</Descriptions.Item>
            </Descriptions>
        )
    })
}

export default Recruitment